import Vue from 'vue'
import VueRouter from 'vue-router'
// 频繁使用的直接加载
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import User from '@/views/layout/user.vue'
import Cart from '@/views/layout/cart.vue'
import Layout from '@/views/layout'
// 会自动找下面的index.vue
// 不频繁使用的懒加载
const Login = () => import('@/views/login')
const store = () => import('@/store')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list.vue')
const Myoder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/user', component: User },
        { path: '/cart', component: Cart }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/myorder', component: Myoder },
    { path: '/pay', component: Pay },
    // 动态路由传参 确认将来是哪个商品,路由参数中携带id
    { path: '/prodetail/:id', component: ProDetail }
  ]
})
// 全局前置导航守卫 所有的路由被访问之前都会经过此守卫 放行后才能到达对应守卫
// to 到哪去(路径,参数)
// from 从哪来(路径,参数)
// next是否放行 next()直接放行 放行到to的路径 next(路径) 拦截到路径
// 定义数组 存放用户需要权限才能访问的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  if (!authUrls.includes(to.path)) {
    // 非权限页面放行
    next()
    return
  }
  // 权限页面看token
  const token = store.getters.token
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
